<script setup lang="ts">
import { fetchRecordDetails, type LogDataRecord } from '@/api/admin/historyRecord'
import { rate } from '@/api/admin/public'

const router = useRouter()

const query = (useRoute().query || {
  medical_record_number: '',
  created_date: '',
}) as {
  medical_record_number: string
  created_date: string
}

const rateResult = ref()

const recordDetails = ref<LogDataRecord | null>(null)

const getRecordDetails = async () => {
  try {
    const response = await fetchRecordDetails(query.medical_record_number, query.created_date)
    if (response) {
      recordDetails.value = response
    }
  } catch (error: any) {
    ElMessage.error(error?.errorDetails.description || error?.message || '未知错误')
  }
}

const question = ref<Record<string, string>>({})

const fechQuestion = async () => {
  try {
    const response = await fetch('http://localhost:8000/static/facial.json')
    if (response.ok) {
      question.value = await response.json()
    }
  } catch (error: any) {
    ElMessage.error('获取评分失败')
    console.error('获取评分失败: ', error)
  }
}

const handleSubmit = async () => {
  if (!rateResult.value && rateResult.value !== 0) {
    ElMessage.warning('请先选择评分')
    return false
  }
  try {
    await rate({
      medical_record_number: query.medical_record_number,
      created_date: query.created_date,
      category: 'facial_expression',
      score: rateResult.value,
    })
    router.push({
      path: '/eyeMovement',
      query: {
        medical_record_number: query.medical_record_number,
        created_date: query.created_date,
      },
    })
  } catch (error) {
    ElMessage.error('评分失败')
    console.error('评分失败: ', error)
  }
}

const handleBack = () => {
  router.push({
    path: '/gait',
    query: {
      medical_record_number: query.medical_record_number,
      created_date: query.created_date,
    },
  })
}

const imgSrcs = computed(() => {
  return [
    recordDetails.value?.facial_expression?.['event_pie.png'],
    recordDetails.value?.facial_expression?.['sentiment_pie.png'],
    recordDetails.value?.facial_expression?.['sentiment_analysis.png'],
  ]
})

const validImgSrcs = computed(() => {
  return imgSrcs.value.filter(Boolean)
})

const videoSrc = computed(() => {
  let src = recordDetails.value?.facial_expression?.['facemesh_processed_video.mp4']
  if (src) {
    src = `http://localhost:8000/${src}`.replace(/\\+/g, '/')
  } else {
    src = ''
  }
  return src
})

onMounted(() => {
  fechQuestion()
  getRecordDetails()
})
</script>

<template>
  <el-row :gutter="48" class="h-full -mr-6">
    <el-col :span="12" class="h-full p-4 flex flex-col justify-center items-center">
      <!-- 视频区域 -->
      <div class="video-container mb-8 w-full">
        <video
          :src="videoSrc"
          controls
          class="w-full h-auto max-h-72 object-contain border rounded-lg shadow-sm mx-auto block"
          v-if="videoSrc"
        />
        <div
          v-else
          class="w-full h-72 bg-gray-100 border rounded-lg flex items-center justify-center text-gray-500 mx-auto"
        >
          暂无视频
        </div>
      </div>

      <!-- 图片轮播区域 -->
      <div class="images-carousel w-full">
        <el-carousel
          indicator-position="outside"
          arrow="hover"
          :autoplay="false"
          :interval="0"
          height="400px"
          v-if="validImgSrcs.length > 0"
        >
          <el-carousel-item v-for="(item, index) in validImgSrcs" :key="index">
            <div class="carousel-item-container">
              <el-image
                :src="`http://localhost:8000/${item}`.replace(/\\+/g, '/')"
                :alt="`分析图${index + 1}`"
                fit="contain"
                class="carousel-image cursor-pointer"
                :preview-src-list="
                  validImgSrcs.map((src) => `http://localhost:8000/${src}`.replace(/\\+/g, '/'))
                "
                :initial-index="index"
                :z-index="3000"
                hide-on-click-modal
                preview-teleported
                lazy
              />
            </div>
          </el-carousel-item>
        </el-carousel>
        <div
          v-else
          class="w-full h-96 bg-gray-100 border rounded-lg flex items-center justify-center text-gray-500"
        >
          暂无图片
        </div>
      </div>
    </el-col>
    <el-col :span="12" class="h-full overflow-auto pr-6">
      <div class="text-brand text-2xl">当前结果：</div>
      <div class="text-#00BA3D font-500 mt-4">
        <span class="text-4xl">{{ rateResult || 0 }}</span>
        <span class="text-lg ml-1">分</span>
      </div>
      <div class="text-brand text-lg mt-4">{{ question[rateResult] || '' }}</div>
      <div class="text-#0167bc text-2xl mt-12">结果修改：</div>
      <el-radio-group v-model="rateResult" class="mt-4">
        <el-radio v-for="rate in Object.keys(question)" :key="rate" :value="Number(rate)">
          {{ question[rate] }}
        </el-radio>
      </el-radio-group>
      <div class="flex items-center justify-evenly gap-8 mt-12">
        <el-button type="primary" class="flex-1" @click="handleSubmit">提交结果</el-button>
        <el-button class="brand-dark-button flex-1" @click="handleBack">返回上一页</el-button>
      </div>
    </el-col>
  </el-row>
</template>

<style lang="css" scoped>
:deep(.el-radio) {
  display: block;
  width: 100%;
}
:deep(.el-radio) {
  --el-color-primary: #508bcc;
  --el-radio-font-size: 16px;
  margin-bottom: 8px;
}
:deep(.el-button) {
  padding: 18px 0;
}

.carousel-item-container {
  height: 100%;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f8f9fa;
  padding: 16px;
  border-radius: 8px;
}

.carousel-image {
  width: 100%;
  height: 100%;
  max-width: 100%;
  max-height: 100%;
}

:deep(.el-image) {
  width: 100% !important;
  height: 100% !important;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s ease-in-out;
}

:deep(.el-image:hover) {
  transform: scale(1.02);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

:deep(.el-image__inner) {
  width: 100% !important;
  height: 100% !important;
  object-fit: contain !important;
  cursor: pointer;
}

:deep(.el-image-viewer__wrapper) {
  z-index: 3001 !important;
}

:deep(.el-image-viewer__mask) {
  background-color: rgba(0, 0, 0, 0.8);
}

:deep(.el-carousel__container) {
  border-radius: 8px;
  overflow: hidden;
  height: 400px !important;
}

:deep(.el-carousel__item) {
  height: 100% !important;
}

:deep(.el-carousel__indicator--horizontal) {
  margin-bottom: 12px;
}

:deep(.el-carousel__button) {
  background-color: #508bcc;
}

:deep(.el-carousel__indicators--outside) {
  margin-top: 16px;
}
</style>
